import time

import jwt

import datetime

__issuer = 'opensys'
JWT_SECRET = 'abc'  # 加解密密钥
JWT_ALGORITHM = 'HS256'  # 加解密算法


def genToken(user_id, h=24):
    dic = {'exp': int(time.time()) + (3600 * h), 'start_time': int(time.time()), 'user_id': user_id}
    token = jwt.encode(dic, JWT_SECRET, algorithm=JWT_ALGORITHM)  # 加密生成字符串
    print(f'生成token => {token}')
    # checkJwtToken(user_id, token)
    return token


def checkJwtToken(user_id, tokenStr: str):
    try:
        token = jwt.decode(tokenStr, JWT_SECRET, algorithms=[JWT_ALGORITHM])
        print(f'解析token成功 => {token}')
    except jwt.PyJWTError:
        print('token解析失败')
        return False
    else:
        exp = int(token.pop('exp'))
        if int(time.time()) > exp:
            print('已失效')
            return False

        if user_id is int(token.pop('user_id')):
            return True
        return False
